package titt.io.util.wrap;

import titt.io.socket.out.TITTOutputStream;
import titt.util.io.pipe.PipeListener;

public class AutoWrapper implements Wrapper {

	private final Wrapper a,b;
	
	public AutoWrapper(Wrapper... w) {
		this(0, w);
	}
	
	private AutoWrapper(int pointer, Wrapper[] w) {
		this.a = w[pointer];
		this.b = pointer == w.length-1? w[pointer] : new AutoWrapper(pointer + 1, w);
	}	
	
	private Wrapper get(Object o) {
		return a.supports(o)? a : b;
	}
	
	@Override
	public String getMimeType(Object o) {
		return get(o).getMimeType(o);
	}

	@Override
	public int getLength(Object o) {
		return get(o).getLength(o);
	}

	@Override
	public boolean supports(Object o) {
		return a.supports(o) || b.supports(o);
	}

	@Override
	public void writeTo(PipeListener listener, TITTOutputStream out, Object o) throws Exception {
		get(o).writeTo(listener, out, o);
	}
	
	private static Wrapper auto = new AutoWrapper(new StringWrapper(), new FileWrapper(), new ByteWrapper(), 
													new NuderContentWrapper(), new NuderStreamWrapper());
	public static Wrapper get() {
		return auto;
	}

}
